package com.leetcode.LC;

import java.util.ArrayList;
import java.util.List;

public class LC238 {
    public int[] productExceptSelf(int[] nums) {

        //考虑0的问题,但是题目要求不能用除法
        int[] ints = new int[nums.length];
        List<Integer> list = new ArrayList<Integer>();
        int sum = 1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                list.add(i);
                continue;
            }
            sum *= nums[i];
        }

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0 && list.isEmpty()) {
                ints[i] = sum / nums[i];
            }
            if (nums[i] != 0 && !list.isEmpty()){
                ints[i]=0;
            }
            if (nums[i] == 0 && list.size()>1){
                ints[i]=0;
            }
            if (nums[i] == 0 && list.size()==1){
                ints[i]=sum;
            }
        }
        return ints;
    }

    public int[] productExceptSelf2(int[] nums) {
        int[] ints = new int[nums.length];
        int[] a = new int[nums.length];
        int[] b = new int[nums.length];
        int sumA=1,sumB=1;

        for (int i = 0; i < nums.length; i++) {
            sumA*=nums[i];
            a[i]=sumA;

            sumB*=nums[nums.length-i-1];
            b[nums.length-i-1]=sumB;
        }
        ints[0]=b[1];
        ints[nums.length-1]=a[nums.length-2];

        for (int i = 1; i < nums.length-1; i++) {
            ints[i]=a[i-1]*b[i+1];
        }
        return ints;
    }

    public static void main(String[] args) {
        for (int i : new LC238().productExceptSelf2(new int[]{1,2,3,4})) {
            System.out.print(i + ",");
        }
    }
}
